//
//  XMHomeViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/18.
//

#import "XMHomeViewController.h"
#import <JXCategoryView/JXCategoryView.h>
#import <JXPagingView/JXPagerListRefreshView.h>
#import "XMHomeHeaderView.h"
#import "XMHomeListViewController.h"
#import "XMHomeNoticeView.h"
#import "XMUserDetailViewController.h"
#import "XMNoticeListViewController.h"
#import "XMRenewVersionView.h"
#import "XMOfficialReminderView.h"

#import "XMPopupView.h"
#import "XMSignView.h"
#import "XMSignModel.h"
#import "XMSignResultView.h"
#import "XMConversationViewController.h"
#import "XMSearchViewController.h"


@interface XMHomeViewController () <JXPagerViewDelegate, JXCategoryViewDelegate, JXPagerMainTableViewGestureDelegate>
@property (nonatomic, strong) JXPagerListRefreshView *pagerView;
@property (nonatomic, strong) JXCategoryTitleView *categoryView;
@property (nonatomic, strong) NSArray <NSString *> *titles;
@property (nonatomic, strong) XMHomeHeaderView *userHeaderView;
@property (nonatomic, strong) UIButton *categoryBtn;
@property (nonatomic, assign) BOOL isHeaderRefreshed;
@property (nonatomic, strong) XMHomeNoticeView *noticeView;
@property (nonatomic, strong) XMRenewVersionView *versionView;
@property (nonatomic, strong) XMSignView *signView;
@property (nonatomic, strong) XMSignResultView *resultView;
@property (nonatomic, strong) XMOfficialReminderView *reminderView;

@property (nonatomic, weak) FGPopupScheduler *scheduler;
@property (nonatomic, copy) NSString *updateLink;
@end

@implementation XMHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    [self setupSubviews];
    [self updateUseInfo];
    [self renewVersion];
    [self bannerList];
    [self applyPopup];
    [self updateLocate];
    [self homeBlock];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self noticeData];
}

- (void)setupNav {
    self.navView.backgroundColor = kHEXA(@"FFFFFF", 0);
    [self.navLeftBtn setImage:nil forState:UIControlStateNormal];
    [self.navLeftBtn setTitle:@"寻觅" forState:UIControlStateNormal];
    [self.navLeftBtn setTitleColor:k1F1F1F forState:UIControlStateNormal];
    self.navLeftBtn.titleLabel.font = kUIFontBold(19);
    
    [self.navLeftBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 44));
    }];
    
    [self.navRightBtn setImage:kGetImage(@"home_sign") forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(signAction:) forControlEvents:UIControlEventTouchUpInside];
    kCornerRadius(self.navRight2Btn, 18, 0, UIColor.clearColor);
    [self.navRight2Btn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(86, 36));
    }];
    
    [self.navRight2Btn setImage:kGetImage(@"home_search") forState:UIControlStateNormal];
    [self.navRight2Btn setTitle:@"搜索" forState:UIControlStateNormal];
    [self.navRight2Btn setTitleColor:k1F1F1F forState:UIControlStateNormal];
    [self.navRight2Btn setImagePosition:XMImagePositionLeft spacing:7];
    [self.navRight2Btn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navRight2Btn.backgroundColor = kHEXA(@"#000000", 0.08);
}

#pragma mark - setupSubviews
- (void)setupSubviews {
    _titles = @[@"精选", @"新人"];
    _userHeaderView = [[XMHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 316 * XMWIDTH)];
    _categoryView = [[JXCategoryTitleView alloc] init];
    self.categoryView.bounds = CGRectMake(0, 0, kScreenWidth, 44);
    self.categoryView.titles = self.titles;
    _categoryView.backgroundColor = kHEXA(@"#8C8F9D", 0.08);
    _categoryView.delegate = self;
    _categoryView.titleSelectedColor = k1F1F1F;
    _categoryView.titleColor = kHEX(@"#535353");
    _categoryView.titleFont = kUIFont(16);
    _categoryView.titleSelectedFont = kUIFontBold(18);
    
    _categoryView.titleColorGradientEnabled = YES;
    //    _categoryView.titleLabelZoomEnabled = YES;
    //    _categoryView.titleLabelZoomScale = 1.125;
    _categoryView.titleLabelStrokeWidthEnabled = YES;
    
    _categoryView.averageCellSpacingEnabled = NO;
    _categoryView.cellSpacing = 24;
    JXCategoryIndicatorImageView *indicatorImageView = [[JXCategoryIndicatorImageView alloc] init];
    indicatorImageView.indicatorImageView.image = [UIImage imageNamed:@"home_idline"];
    indicatorImageView.indicatorImageViewSize = CGSizeMake(14, 5);
    indicatorImageView.verticalMargin = 2;
    _categoryView.indicators = @[indicatorImageView];
    
    [self.categoryView addSubview:self.categoryBtn];
    [self.categoryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.categoryView).offset(-24);
        make.centerY.equalTo(self.categoryView);
    }];
    
    _pagerView = [[JXPagerListRefreshView alloc] initWithDelegate:self];
    self.pagerView.pinSectionHeaderVerticalOffset = kNavBarAndStatusBarHeight;
    
    [self.view addSubview:self.pagerView];
    
    self.categoryView.listContainer = (id<JXCategoryViewListContainer>)self.pagerView.listContainerView;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = (self.categoryView.selectedIndex == 0);
    
    [self.view bringSubviewToFront:self.navView];
    
    self.pagerView.mainTableView.bounces = NO;
    [self.view addSubview:self.noticeView];
    [self.noticeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(30);
        make.top.equalTo(self.navView.mas_bottom);
    }];
}

#pragma mark - initData
- (void)updateUseInfo {
    NSMutableDictionary *dic = @{
        @"module": @"3"
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            XMUserModel *model = [XMUserModel mj_objectWithKeyValues:result];
            kUserModel = model;
            [self signData];
        }
    }];
}

- (void)signData {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/activity/signBoard/detail" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
//        self.navRightBtn.enabled = YES;
        if (tip.success) {
            self.signView.model = [XMSignModel mj_objectWithKeyValues:result];
            if (kUserModel.today_sign_status.intValue == 0) {
                self.signView.signBtn.enabled = NO;
            } else {
                self.signView.signBtn.enabled = YES;
                [self showSignView];
            }
        }
    }];
}

- (void)bannerList {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/activityData" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            NSArray *arr = [result safe_objectForKey:@"record"];
            self.userHeaderView.dataArray = [XMBannerModel mj_objectArrayWithKeyValuesArray:arr];
        }
    }];
}

- (void)noticeData {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/noticeData" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            NSArray *array = [result safe_objectForKey:@"title"];
            NSInteger unread = [result toInt:@"unread"];
            [self.noticeView setupTitles:array unread:unread];
        }
    }];
}

- (void)updateLocate {
    if (![XMLoginManager.sharedInstance isLogin]) {
        return;
    }
    NSMutableDictionary *dic = @{
        @"longitude": @([kMMKV getDoubleForKey:kUserLongitude]),
        @"latitude": @([kMMKV getDoubleForKey:kUserLatitude])
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/locate" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
    }];
}

- (void)applyPopup {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/applyPopup" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            XMOfficialReminderModel *model = [XMOfficialReminderModel mj_objectWithKeyValues:result];
            if (model.status) {
                XMWeakSelf(self);
                [self.reminderView setupModel:model
                                     complete:^{
                    XMStrongSelf(self);
                    [self showReminderView];
                }];
            }
        }
    }];
}

- (void)renewVersion {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/auth/renewVersion" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            NSString *localVerson = [[XMUtil bundleShortVersionString] stringByReplacingOccurrencesOfString:@"." withString:@""];
            NSString *appVersion = [[result toString:@"appVersion"] stringByReplacingOccurrencesOfString:@"." withString:@""];
            self.updateLink = [result toString:@"updateLink"];
            NSInteger forcedCode = [result toInt:@"forcedCode"];
            NSString *updateDesc = [result toString:@"updateDesc"];
            BOOL needUpdate = localVerson.intValue < appVersion.intValue;
            if (needUpdate) {
                self.versionView.closeBtn.hidden = forcedCode == 1;
                self.versionView.contentLa.text = updateDesc;
                [self showVersionView];
            }
        }
    }];
}

- (void)showSignView {
    XMPopupView *popView = [[XMPopupView alloc] initWithContentView:self.signView fromView:kWindow scheduler:self.scheduler];
    popView.switchBehavior = FGPopupViewSwitchBehaviorLatent;
    [self.scheduler add:popView Priority:FGPopupStrategyPriorityLow];
    self.signView.closeBlock = ^{
        [popView dismissPopupView];
    };
    popView.touchCallBack = ^{};
    XMWeakSelf(self);
    self.signView.signBlock = ^(NSString * _Nonnull index) {
        XMStrongSelf(self);
        [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
        NSMutableDictionary *dic = @{
            @"index": index
        }.mutableCopy;
        
        XMWeakSelf(self);
        [YHNetworkManager.sharedInstance postWithUrl:@"api/activity/signBoard/handle" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            XMStrongSelf(self);
            if (tip.success) {
                [popView dismissPopupView];
                [MBProgressHUD hideHUD];
                
                kUserModel.today_sign_status = @(0);
                self.signView.signBtn.enabled = NO;
                
                [self signData];
                
                NSString *reward_type = [result toString:@"reward_type"];
                NSString *reward_title = [result toString:@"reward_title"];
                NSString *reward_msg = [result toString:@"reward_msg"];
                switch (reward_type.intValue) {
                    case 10001:
                    case 20001: {
                        [MBProgressHUD showHUDMsg:reward_msg toView:kWindow];
                    } break;
                    case 40001:
                    case 40002:
                    case 40003:
                    case 40004:
                    case 40005: {
                        self.resultView.typeLa.text = reward_title;
                        self.resultView.tipLa.text = reward_msg;
                        [self showSignResultView];
                    } break;
                    default:
                        break;
                }
            }
        }];
    };
}

#pragma mark - homeBlock
- (void)homeBlock {
    XMWeakSelf(self);
    self.noticeView.tapBlock = ^{
        XMStrongSelf(self);
        XMNoticeListViewController *vc = [[XMNoticeListViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    self.userHeaderView.webBlock = ^(XMBannerModel * _Nonnull model) {
        XMStrongSelf(self);
        if ([XMUtil isBlankString:model.link]) {
            return;
        }
        XMWebViewController *vc = [[XMWebViewController alloc] init];
        vc.titleStr = model.title;
        vc.urlStr = model.link;
        vc.needNav = YES;
        [self.navigationController pushViewController:vc animated:YES];
    };
}

#pragma mark - Actions
- (void)signAction:(UIButton *)sender {
//    sender.enabled = NO;
    [self showSignView];
//    if (kUserModel.today_sign_status.intValue == 0) {
//        [self showSignView];
//    } else {
//        [self signData];
//    }
}

- (void)searchAction:(UIButton *)sender {
    XMSearchViewController *vc = [[XMSearchViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.pagerView.frame = self.view.bounds;
}

#pragma mark - JXPagingViewDelegate

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return self.userHeaderView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return 316 * XMWIDTH;
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return 44;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.categoryView;
}

- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    return self.titles.count;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    XMHomeListViewController *list = [[XMHomeListViewController alloc] init];
    list.type = index;
    XMWeakSelf(self);
    list.detailBlock = ^(XMUserModel * _Nonnull model) {
        XMStrongSelf(self);
        XMUserDetailViewController *vc = [[XMUserDetailViewController alloc] init];
        vc.userId = model.user_id;
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    list.chatBlock = ^(XMUserModel * _Nonnull model) {
        XMStrongSelf(self);
        XMConversationViewController *conversationVC = [[XMConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:model.user_id];
        conversationVC.conversationType = ConversationType_PRIVATE;
        conversationVC.targetId = model.user_id;
        conversationVC.titleStr = model.showName;
        conversationVC.unReadMessage = 0;
        conversationVC.enableNewComingMessageIcon = YES; //开启消息提醒
        conversationVC.enableUnreadMessageIcon = YES;
        [self.navigationController pushViewController:conversationVC animated:YES];
    };
    
    return list;
}

- (void)pagerView:(JXPagerView *)pagerView mainTableViewDidScroll:(UIScrollView *)scrollView {
    CGFloat thresholdDistance = 200;
    CGFloat percent = scrollView.contentOffset.y / thresholdDistance;
    percent = MAX(0, MIN(1, percent));
    self.navView.hidden = scrollView.contentOffset.y < 0 ? YES : NO;
    self.navView.backgroundColor = kHEXA(@"FFFFFF", percent);
//    if (percent >= 1) {
//        [self.categoryBtn removeAllTargets];
//        [self.categoryBtn addTarget:self action:@selector(filterAction) forControlEvents:UIControlEventTouchUpInside];
//        [self.categoryBtn setTitle:@"筛选" forState:UIControlStateNormal];
//        [self.categoryBtn setImage:kGetImage(@"home_shaixuan") forState:UIControlStateNormal];
//        self.noticeView.hidden = YES;
//    } else {
//        [self.categoryBtn removeAllTargets];
//        [self.categoryBtn addTarget:self action:@selector(exchangeAction) forControlEvents:UIControlEventTouchUpInside];
//        [self.categoryBtn setTitle:@"换一批" forState:UIControlStateNormal];
//        [self.categoryBtn setImage:kGetImage(@"home_huan") forState:UIControlStateNormal];
//        self.noticeView.hidden = NO;
//    }
}

#pragma mark - JXCategoryViewDelegate
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
}


#pragma mark - JXPagerMainTableViewGestureDelegate
- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    //    if (otherGestureRecognizer == (UIView *)self.userHeaderView.bannerView.panGestureRecognizer) {
    //        return NO;
    //    }
    
    if (otherGestureRecognizer == self.categoryView.collectionView.panGestureRecognizer) {
        return NO;
    }
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}


- (UIButton *)categoryBtn {
    if (_categoryBtn == nil) {
        _categoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_categoryBtn setImage:kGetImage(@"home_huan") forState:UIControlStateNormal];
        [_categoryBtn setTitle:@"换一批" forState:UIControlStateNormal];
        [_categoryBtn setImagePosition:(XMImagePositionLeft) spacing:6];
        [_categoryBtn setTitleColor:kAppMainColor forState:UIControlStateNormal];
        _categoryBtn.titleLabel.font = kUIFont(14);
        [_categoryBtn addTarget:self action:@selector(exchangeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _categoryBtn;
}

- (void)exchangeAction {
    [MBProgressHUD showHUDActivityMsg:nil];
    [kNotificationCenter postNotificationName:@"homeListDataRefresh" object:nil];
}

- (void)filterAction {
    XMLog(@"筛选");
}

- (XMHomeNoticeView *)noticeView {
    if (_noticeView == nil) {
        _noticeView = [XMHomeNoticeView viewFromXib];
    }
    return _noticeView;
}

- (XMRenewVersionView *)versionView {
    if (_versionView == nil) {
        _versionView = [XMRenewVersionView viewFromXib];
        _versionView.size = UIScreen.mainScreen.bounds.size;
    }
    return _versionView;
}

- (XMSignView *)signView {
    if (!_signView) {
        _signView = [XMSignView viewFromXib];
        _signView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _signView;
}
- (FGPopupScheduler *)scheduler {
    if (!_scheduler) {
        _scheduler = FGPopupSchedulerGetForPSS(FGPopupSchedulerStrategyPriority);
    }
    return _scheduler;
}

- (XMSignResultView *)resultView {
    if (!_resultView) {
        _resultView = [XMSignResultView viewFromXib];
        _resultView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _resultView;
}

- (void)showSignResultView {
    XMPopupView *popView = [[XMPopupView alloc] initWithContentView:self.resultView fromView:kWindow scheduler:self.scheduler];
    popView.switchBehavior = FGPopupViewSwitchBehaviorLatent;
    [self.scheduler add:popView Priority:FGPopupStrategyPriorityLow + 1];
    self.resultView.closeBlock = ^{
        [popView dismissPopupView];
    };
    popView.touchCallBack = ^{};
}


- (void)showVersionView {
    XMPopupView *popView = [[XMPopupView alloc] initWithContentView:self.versionView fromView:kWindow scheduler:self.scheduler];
    popView.switchBehavior = FGPopupViewSwitchBehaviorLatent;
    [self.scheduler add:popView Priority:FGPopupStrategyPriorityVeryHigh];
    self.versionView.closeBlock = ^{
        [popView dismissPopupView];
    };
    
    XMWeakSelf(self);
    self.versionView.updateBlock = ^{
        XMStrongSelf(self);
        NSURL *url = [NSURL URLWithString:self.updateLink];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success){}];
    };
    
    popView.touchCallBack = ^{};
}

- (XMOfficialReminderView *)reminderView {
    if (!_reminderView) {
        _reminderView = [XMOfficialReminderView viewFromXib];
        _reminderView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _reminderView;
}

- (void)showReminderView {
    XMPopupView *popView = [[XMPopupView alloc] initWithContentView:self.reminderView fromView:kWindow scheduler:self.scheduler];
    popView.switchBehavior = FGPopupViewSwitchBehaviorLatent;
    [self.scheduler add:popView Priority:FGPopupStrategyPriorityLow + 2];
    popView.touchCallBack = ^{};
    XMWeakSelf(self);
    self.reminderView.tapBlock = ^(XMOfficialReminderModel * _Nonnull model) {
        XMStrongSelf(self);
        XMWebViewController *vc = [[XMWebViewController alloc] init];
        vc.titleStr = model.title;
        vc.urlStr = model.link;
        vc.needNav = YES;
        [self.navigationController pushViewController:vc animated:YES];
        [popView dismissPopupView];
    };
    
    self.reminderView.closeBlock = ^{
        [popView dismissPopupView];
    };
}

@end
